﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace NewBootTrap
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Timer timer1;
		private System.ComponentModel.IContainer components;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.label1 = new System.Windows.Forms.Label();
            this.timer1 = new System.Windows.Forms.Timer(this.components);
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(10, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(278, 19);
            this.label1.TabIndex = 0;
            this.label1.Text = "Loading...";
            // 
            // timer1
            // 
            this.timer1.Enabled = true;
            this.timer1.Interval = 2000;
            this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
            this.ClientSize = new System.Drawing.Size(248, 29);
            this.Controls.Add(this.label1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "WebUpdate BOOTSTRAP";
            this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main( string[] args ) 
		{            
			if ( args.Length == 0 )
			{
				Application.Run(new Form1());
			}
			else
			{
				#region checkifupdates
				try
				{
					int numberUpdate = GetNumberToUpdate();                    
					if ( numberUpdate > 0 )
					{
						if ( MessageBox.Show( "Install path : " + Application.StartupPath + "\r\n" + "An update is available ! ( " + numberUpdate + " Files updates ) \r\nDou you want to update now ?", "WEBUPDATE", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes )
						{
							MessageBox.Show("Please close the soft then click OK", "Update", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
							//start web update

							System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
							psi.FileName = Application.StartupPath + "\\WebUpdate.exe";
							psi.UseShellExecute = true;
							psi.WorkingDirectory = Application.StartupPath;

							System.Diagnostics.Process.Start( psi );
							Application.Exit();
						}
						else
						{
							Application.Exit();
						}
					}
				}
				catch(Exception ex)
				{
                    MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
					Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
				}
					#endregion
					
			}
			

		}

		public static int GetNumberToUpdate()
		{
			int total = 0;
			
			string version = "";

			if ( !System.IO.File.Exists( Application.StartupPath + "\\WebUpdate.ini" ) )
			{
				System.IO.FileStream fs = System.IO.File.Create( Application.StartupPath + "\\WebUpdate.ini" );
				fs.Close();
			}

			ini i = new ini(Application.StartupPath + "\\WebUpdate.ini");
			version = i.IniReadValue("General", "Version");

			if (version == "")
			{
				version = "PUBLIC";
				i.IniWriteValue("General", "Version", version);
			}

			WebUpdate.ws_update.Update upd = new WebUpdate.ws_update.Update();           
			object[] updates = upd.GetAllUpdateInfosCompressed(version);

			if (updates == null)
			{ 
				return -1;
			}

			foreach ( object o in updates )
			{
				WebUpdate.ws_update.UpdateInfos ui = (WebUpdate.ws_update.UpdateInfos)o;
				//Kiểm tra xem trong thư mục bên client có file đó chưa và so sánh thời gian tạo file
				if ( !System.IO.File.Exists( Application.StartupPath + ui.filepath ) || System.IO.File.GetCreationTimeUtc( Application.StartupPath + ui.filepath ) < ui.time.ToUniversalTime() )
				{
					int comp = ui.filepath.ToUpper().IndexOf("COMPRESSIONEXTENSION.DLL");
					int sharp = ui.filepath.ToUpper().IndexOf("SHARPZIPLIB.DLL");
				
					if ( (comp == -1) && ( sharp == -1) )
					{
						total += 1;
					}
					else
					{
						int bad = 1;
					}
				}
		
			}

			
			return total;

        }

		private void timer1_Tick(object sender, System.EventArgs e)
		{
			timer1.Enabled = false;
			timer1.Stop();

			#region boostrap
			string version = "";

			if ( !System.IO.File.Exists( Application.StartupPath + "\\WebUpdate.ini" ) )
			{
				System.IO.FileStream fs = System.IO.File.Create( Application.StartupPath + "\\WebUpdate.ini" );
				fs.Close();
			}

			ini i = new ini(Application.StartupPath + "\\WebUpdate.ini");
            //lấy tên thư mục cần update
			version = i.IniReadValue("General", "Version");

			if (version == "")
			{
				version = "PUBLIC";
				i.IniWriteValue("General", "Version", version);
			}

			WebUpdate.ws_update.Update upd = new WebUpdate.ws_update.Update();
			object[] updates = upd.GetAllUpdateInfosCompressed(version);

			if (updates == null)
			{
				MessageBox.Show( "No files on the update server or your ini file is not correct !");
				return;
			}

			foreach ( object o in updates )
			{
				WebUpdate.ws_update.UpdateInfos ui = (WebUpdate.ws_update.UpdateInfos)o;
				
				//In case we update webupdateclient 
				if (ui.filepath.ToUpper() == "\\WEBUPDATECLIENT.EXE")
				{
					if ( !System.IO.File.Exists( Application.StartupPath + ui.filepath ) || System.IO.File.GetCreationTimeUtc( Application.StartupPath + ui.filepath ) < ui.time.ToUniversalTime() )
					{
						WebUpdate.ws_update.UpdateInfos ui2 = upd.GetFileCompressed( version, ui.filepath.Replace("\\", "/") );
						
						System.IO.FileStream fs2 = System.IO.File.Create( Application.StartupPath + ui.filepath );
						fs2.Write( ui2.bin, 0, (int)ui2.bin.Length );
						fs2.Close();
						System.IO.File.SetCreationTimeUtc( Application.StartupPath + ui.filepath, ui2.time.AddMinutes(5));

					}

				}
		
			}
			#endregion

			//start the real updater
			System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
			psi.FileName = Application.StartupPath + "\\WebUpdateClient.exe";
			psi.UseShellExecute = true;
			psi.WorkingDirectory = Application.StartupPath;

			System.Diagnostics.Process.Start( psi );
			Application.Exit();
		}
	}
}
